<?php
namespace app\lib\baidu;
use think\Db;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\Http\BceHttpClient;

class DeliApi 
{

    public function token($api_param=[]){
        $params = [
            'client_id'=>$api_param['client_id'],
            'client_secret'=>$api_param['client_secret'],
            'grant_type'=>'client_credentials'
        ];
        $api_url = 'https://aip.baidubce.com/oauth/2.0/token';
        $result = httpRequest($api_url,$params,'POST',[
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
        $result = json_decode($result,true);
        return $result;
    }

    public function imageUpload($image,$brief,$tags=''){
        $token = $this->token([
            'client_id'=>'IrpWRObU54EpdyoLWKo6w5bf',
            'client_secret'=>'Rkrab1jbopznKvSSBrGKg16wRzspR2o0'
        ]);
        if (empty($token['access_token'])) {
            return ['status'=>0,'msg'=>$token['error_description']];
        }
        $access_token = $token['access_token'];
        $api_url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/add?access_token='.$access_token;
        $params = [
            'url'=>$image,
            'brief'=>$brief
        ];
        if (!empty($tags)) {
            $params['tags'] = $tags;
        }

        $result = httpRequest($api_url,$params,'POST',[
                'Content-Type: application/x-www-form-urlencoded',
            ]);
        $result = json_decode($result,true);
        if (empty($result['error_code'])) {
            return ['status'=>1,'cont_sign'=>$result['cont_sign']];
        }else{
            return ['status'=>0,'msg'=>$result['error_msg']];
        }
    }

    public function imageSearch($params){
        $token = $this->token([
            'client_id'=>'mwRvsfrVyBLXLd3ouoH4MIkl',
            'client_secret'=>'vYDjgq9b8gBQ9rhfXIroaJr5R9CSSRLo'
        ]);
        if (empty($token['access_token'])) {
            return ['status'=>0,'msg'=>$token['error_description']];
        }
        $access_token = $token['access_token'];
        $api_url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/search?access_token='.$access_token;
        $result = httpRequest($api_url,$params,'POST',[
                'Content-Type: application/x-www-form-urlencoded',
            ]);
        // $result = '{"has_more":false,"result":[{"score":1,"cont_sign":"1283258944,4202501915"}],"result_num":1,"log_id":1856579920988790548}';
        $result = json_decode($result,true);
        if (empty($result['error_code'])) {
            return ['status'=>1,'has_more'=>$result['has_more'],'list'=>$result['result'],'num'=>$result['result_num']];
        }else{
            return ['status'=>0,'msg'=>$result['error_msg']];
        }
    }

    public function ocr_token(){
        $params = [
            // 'client_id'=>'IAs69XvwAziM9onV9kxB1DHM',
            // 'client_secret'=>'74iCbnVp8oPB4WYGaCnqpK91j6oPbwQ3',
            'client_id'=>'DVJOzu2Fh6KgpfUcUtZMM6ip',
            'client_secret'=>'9oimvgSFnzpXVjgAmPpn1gmZ9bB2JAqh',
            'grant_type'=>'client_credentials'
        ];
        $api_url = 'https://aip.baidubce.com/oauth/2.0/token';
        $result = httpRequest($api_url,$params,'POST',[
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
        $result = json_decode($result,true);
        return $result;
    }

    public function htsc($file_url,$type){
        $token = $this->ocr_token();
        if (empty($token['access_token'])) {
            return ['status'=>0,'msg'=>$token['error_description']];
        }
        $access_token = $token['access_token'];
        $api_url = 'https://aip.baidubce.com/file/2.0/brain/online/v1/textreview/task?access_token='.$access_token;
        $params = [
            'fileURLList'=>$file_url,
            'templateName'=>$type
        ];
        $result = httpRequest($api_url,$params,'POST',[
                'Content-Type: multipart/form-data',
            ]);
        $result = json_decode($result,true);
        if ($result['error_code'] == '0') {
            return ['status'=>1,'task_id'=>$result['result']['taskId']];
        }else{
            return ['status'=>0,'msg'=>$result['error_msg']];
        }
    }

    public function htscTask($task_id){
        $token = $this->ocr_token();
        if (empty($token['access_token'])) {
            return ['status'=>0,'msg'=>$token['error_description']];
        }
        $access_token = $token['access_token'];
        // dump($access_token);die;
        $api_url = 'https://aip.baidubce.com/file/2.0/brain/online/v1/textreview/task/query?access_token='.$access_token;
        $params = [
            'taskId'=>$task_id,
        ];
        $result = httpRequest($api_url,$params,'POST',[
                'Content-Type: multipart/form-data',
            ]);
        $result = json_decode($result,true);
        if ($result['error_code'] == '0') {
            if ($result['result']['status'] == 'success') {
                return ['status'=>1,'data'=>$result['result']['textreviewResult']];    
            }elseif($result['result']['status'] == 'failed'){
                return ['status'=>-1,'reason'=>$result['result']['reason']];    
            }else{
                return ['status'=>0,'msg'=>$result['error_msg']];
            }
        }else{
            return ['status'=>0,'msg'=>$result['error_msg']];
        }
    }

    public function chat($api_url,$access_token,$messages,$system=''){
        // $token = $this->token();
        // if (empty($token['access_token'])) {
        //     return ['status'=>0,'msg'=>$token['error_description']];
        // }
        // $access_token = $token['access_token'];
        $api_url = $api_url.'?access_token='.$access_token;
        $params = [
            'messages'=>$messages
        ];
        if (!empty($system)) {
            $params['system'] = $system;
        }
        $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
        Db::name('test')->insert(['content'=>'-----'.$result]);
        Db::name('test')->insert(['content'=>'-----'.json_encode($params,JSON_UNESCAPED_UNICODE)]);
        
        $result = json_decode($result,true);
        if ( !empty($result['result']) ) {
            if ( $result['usage']['completion_tokens'] > 0 ) {
                return ['status'=>1,'answer'=>$result['result']];
            }else{
                return ['status'=>2,'answer'=>$result['result']];
            }
        }else{
            return ['status'=>0,'msg'=>$result['error_msg']];
        }
    }

    public function txt2imgv2($access_token,$params){
        $api_url = 'https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2imgv2';
        $api_url = $api_url.'?access_token='.$access_token;
        $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
        // $result = '{"data":{"primary_task_id":1770752066464521544,"task_id":"1770752066464521544"},"log_id":1770752066464521544}';
        Db::name('test')->insert(['content'=>'-----'.$result]);
        Db::name('test')->insert(['content'=>'-----'.json_encode($params,JSON_UNESCAPED_UNICODE)]);
        
        $result = json_decode($result,true);
        if (empty($result['error_code'])) {
            return ['status'=>1,'task_id'=>$result['data']['task_id']];
        }else{
            return ['status'=>0,'msg'=>$result['error_msg']];
        }
    }

    public function aidrawTask($access_token,$task_id){
        $api_url = 'https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImgv2?access_token='.$access_token;
        $params = [
            'task_id'=>$task_id,
        ];
        $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
        $result = json_decode($result,true);
        if (empty($result['error_code'])) {
            if ($result['data']['task_status'] == 'SUCCESS') {
                return ['status'=>1,'data'=>$result['data']['sub_task_result_list']];    
            }elseif($result['data']['task_status'] == 'FAILED'){
                return ['status'=>-1,'reason'=>'灰白'];    
            }
        }else{
            return ['status'=>0,'msg'=>$result['error_msg']];
        }
    }

    public function singleOptimize($message){
        $configs = array(
            'credentials' => array(
                'ak' => 'ec886ce24a7d4559be918c7624fea1db',
                'sk' => '7aefaaa8efad448eafed92cf7e5bcc7c',
            ),
            'endpoint' => 'https://qianfan.baidubce.com',
        );

        $method = 'POST';
        $parh = "/wenxinworkshop/prompt/singleOptimize/create";
        $body = [
            'content'=>$message,
            'operations'=>[
                ['opType'=>1,'payload'=>1],
                ['opType'=>2,'payload'=>1],
                ['opType'=>3,'payload'=>1],
                ['opType'=>4,'payload'=>0],
            ]
        ];
        $body = json_encode($body,JSON_UNESCAPED_UNICODE);
        $params = json_decode('{"charset":"UTF-8"}',true);
        $headers = array( 
            'Content-Type' => 'application/json',
        );

        try{
          $response = (new BceHttpClient())->sendRequest(
            $configs,
            $method,
            $parh,
            $body,
            $headers,
            $params,
            new BceV1Signer()
          );
            $body = json_decode($response['body'],true);
            if ($body['status'] == '200') {
                return ['status'=>1,'data'=>$body['result']];
            }else{
                return ['status'=>0,'msg'=>$body['message']['global']];    
            }
        }catch(\Exception $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    public function singleOptimizeInfo($task_id){
        $configs = array(
            'credentials' => array(
                'ak' => 'ec886ce24a7d4559be918c7624fea1db',
                'sk' => '7aefaaa8efad448eafed92cf7e5bcc7c',
            ),
            'endpoint' => 'https://qianfan.baidubce.com',
        );

        $method = 'POST';
        $parh = "/wenxinworkshop/prompt/singleOptimize/info";
        $body = [
            'id'=>$task_id,
        ];
        $body = json_encode($body,JSON_UNESCAPED_UNICODE);
        $params = json_decode('{"charset":"UTF-8"}',true);
        $headers = array( 
            'Content-Type' => 'application/json',
        );

        try{
          $response = (new BceHttpClient())->sendRequest(
            $configs,
            $method,
            $parh,
            $body,
            $headers,
            $params,
            new BceV1Signer()
          );
            $body = json_decode($response['body'],true);
            if ($body['status'] == '200') {
                return ['status'=>1,'data'=>$body['result']];
            }else{
                return ['status'=>0,'msg'=>$body['message']['global']];    
            }
        }catch(\Exception $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    
    
    public function chat2($message){
        $token = $this->token();
        if (empty($token['access_token'])) {
            return ['status'=>0,'msg'=>$token['error_description']];
        }
        $access_token = $token['access_token'];
        $messages = [];
        $api_url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token='.$access_token;

        
        $messages[] = [
            'role'=>'user',
            'content'=>$message
        ];

        if (count($messages) > 1 && count($messages) % 2 == 0) {
            array_shift($messages);
        }
        $params = [
            'messages'=>$messages,
            'temperature'=>0.1,
            'system'=>'你是云计算考官'
        ];
        $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
        // Db::name('test')->insert(['content'=>$result]);
        // Db::name('test')->insert(['content'=>json_encode($params,JSON_UNESCAPED_UNICODE)]);
        
        $result = json_decode($result,true);
        // dump($params);
        // dump($result);die;
        if ( !empty($result['result']) ) {
            if ( $result['usage']['completion_tokens'] > 0 ) {
                return ['status'=>1,'answer'=>$result['result']];
            }else{
                return ['status'=>2,'answer'=>$result['result']];
            }
        }else{
            return ['status'=>0,'msg'=>$result['error_msg']];
        }
    }
}
